<!DOCTYPE html>
<html lang="pt">
<head>
    <meta charset="UTF-8">
    <title>Dopamine Rush - Duelo PvE (Offline)</title>
    <style>
        /* --- ESTILOS GERAIS E DO JOGO --- */
        html, body { height: 100%; margin: 0; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #1a1a2e; color: #e0e0e0; overflow: hidden; }
        .container { max-width: 960px; margin: auto; text-align: center; padding: 20px; }
        #game-section { display: none; flex-direction: row; height: 100vh; padding: 10px; box-sizing: border-box; gap: 15px; }
        #left-panel, #right-panel { flex: 1; display: flex; flex-direction: column; padding: 10px; background-color: rgba(0,0,0,0.2); border-radius: 8px; min-width: 220px; max-width: 250px; overflow-y: auto; }
        #center-panel { flex: 3; display: flex; flex-direction: column; align-items: center; min-width: 600px; position: relative; }
        #right-panel { min-width: 260px; max-width: 300px; }
        #left-panel h3 { text-align: center; margin-bottom: 10px; color: #a9a9d4;}
        #focused-card-view { width: 90%; max-width: 220px; aspect-ratio: 2.5 / 3.5; background-color: #34495e; border: 2px solid #4a617a; border-radius: 10px; margin: 0 auto; display: flex; align-items: center; justify-content: center; overflow: hidden; cursor: pointer; }
        #focused-card-view img { max-width: 100%; max-height: 100%; border-radius: 7px; }
        #focused-card-view span { font-style: italic; color: #95a5a6; font-size: 0.9em; text-align: center; padding: 5px; }
        #board { display: grid; grid-template-columns: repeat(7, 1fr); grid-template-rows: repeat(4, 1fr); gap: 8px; width: 100%; height: 100%; background: #16213e; border: 3px solid #533e85; padding: 10px; box-sizing: border-box; position: relative; border-radius: 10px; transition: box-shadow 0.3s ease; }
        #board.attack-mode-active { box-shadow: 0 0 20px rgba(231, 76, 60, 0.6); }
        .card-slot { border: 2px dashed rgba(173, 216, 230, 0.2); border-radius: 6px; background-color: rgba(0, 0, 0, 0.2); display: flex; align-items: center; justify-content: center; font-size: 0.7em; color: rgba(255, 255, 255, 0.4); position: relative; overflow: hidden; text-align: center; transition: background-color 0.2s, border-color 0.2s; cursor: pointer; }
        .card-slot.hand { background-color: rgba(44, 62, 80, 0.5); }
        .card-slot.deck { background-color: rgba(142, 68, 173, 0.5); font-weight: bold; color: white; }
        .card-slot.discard { background-color: rgba(192, 57, 43, 0.5); }
        .card-slot.battlefield { background-color: rgba(52, 152, 219, 0.2); }
        .card-slot.avatar-slot { border: 2px solid #a9a9d4; background-color: rgba(241, 196, 15, 0.1); }
        #OpponentHand1{grid-area:1/1} #OpponentHand2{grid-area:1/2} #OpponentHand3{grid-area:1/3}
        #OpponentDeck{grid-area:1/7;} #OpponentAvatar{grid-area:2/1} #OpponentCreature1{grid-area:2/2}
        #OpponentCreature2{grid-area:2/3} #OpponentCreature3{grid-area:2/4} #OpponentDiscard{grid-area:2/6;}
        #PlayerAvatar{grid-area:3/1} #PlayerCreature1{grid-area:3/2} #PlayerCreature2{grid-area:3/3}
        #PlayerCreature3{grid-area:3/4} #PlayerDiscard{grid-area:3/6;} #PlayerHand1{grid-area:4/1}
        #PlayerHand2{grid-area:4/2} #PlayerHand3{grid-area:4/3} #PlayerDeck{grid-area:4/7;}
        .card { position: absolute; width: 100px; height: 140px; transition: all 0.4s ease-in-out; pointer-events: auto; cursor: pointer; z-index: 10; border: 2px solid #111; border-radius: 8px; overflow: hidden; background-color: #555; display: flex; justify-content: center; align-items: center; box-shadow: 3px 3px 8px rgba(0,0,0,0.5); }
        .card:hover { transform: scale(1.1); z-index: 100; }
        .card.selected { border-color: #ffdd57; box-shadow: 0 0 15px #ffdd57; }
        .card.tapped { transform: rotate(90deg) scale(0.95); z-index: 9; }
        .card img { width: 100%; height: 100%; object-fit: cover; }
        .card-stats-display { position: absolute; bottom: 3px; right: 5px; background-color: rgba(0, 0, 0, 0.8); color: white; padding: 2px 5px; border-radius: 4px; font-size: 0.9em; font-weight: bold; pointer-events: none; }
        #turn-indicator { padding: 12px; margin-bottom: 10px; text-align: center; font-size: 1.4em; font-weight: bold; border-radius: 8px; transition: background-color 0.3s; }
        .player-turn { background-color: #2980b9; color: white; }
        .opponent-turn { background-color: #c0392b; color: white; }
        .main-action-button { width: 100%; padding: 8px; border: none; border-radius: 5px; cursor: pointer; font-weight: bold; background-color: #34495e; color: #ecf0f1; transition: background-color 0.2s; margin-top: 10px; }
        .main-action-button:hover { background-color: #4a617a; }
        .main-action-button:disabled { background-color: #7f8c8d; cursor: not-allowed; }
        #attack-mode-btn.attack-mode-active { background-color: #e67e22; box-shadow: 0 0 10px #f39c12; }
        .resource-display { display: flex; justify-content: space-around; background-color: rgba(0,0,0,0.3); padding: 8px; border-radius: 4px; margin-bottom: 10px; }
        .card.attacker-selected { border: 3px solid #f1c40f; box-shadow: 0 0 20px #f1c40f; transform: scale(1.05); }
        .card-slot.valid-target { cursor: crosshair !important; border-color: #e74c3c !important; border-style: solid !important; background-color: rgba(231, 76, 60, 0.3); }

        /* --- ESTILOS DO MENU --- */
        #menu-section h1, #menu-section h2 { color: #ffdd57; text-transform: uppercase; letter-spacing: 1.5px; }
        #opponent-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 25px; margin-top: 30px; text-align: left; }
        .opponent-card { background: #2a2a2a; border: 1px solid #533e85; border-radius: 12px; cursor: pointer; transition: transform 0.2s, box-shadow 0.2s; overflow: hidden; display: flex; flex-direction: column; }
        .opponent-card:hover { transform: translateY(-5px); box-shadow: 0 5px 20px #a9a9d430; border-color: #a9a9d4; }
        .opponent-portrait { width: 100%; height: 160px; object-fit: cover; }
        .opponent-info { padding: 15px; }
        .opponent-info h3 { margin-top: 0; margin-bottom: 5px; color: #a9a9d4; font-size: 1.4em; }
        .opponent-description { font-size: 0.9em; color: #b0b0c0; margin-top: 0; margin-bottom: 10px; min-height: 40px; }
        .difficulty-tag { display: inline-block; padding: 3px 8px; border-radius: 5px; font-size: 0.8em; font-weight: bold; color: #111; }
        .difficulty-fácil { background-color: #2ecc71; }
        .difficulty-média { background-color: #f1c40f; }
        .difficulty-difícil { background-color: #e74c3c; }
        .rewards-preview { border-top: 1px solid #444; padding: 15px; margin-top: auto; background-color: rgba(0,0,0,0.2); }
        .rewards-preview h4 { margin-top: 0; margin-bottom: 10px; font-size: 0.9em; text-transform: uppercase; color: #ffdd57; letter-spacing: 1px; }
        .rewards-preview ul { list-style: none; padding: 0; margin: 0; font-size: 0.9em; }
        .rewards-preview li { margin-bottom: 5px; }
    </style>
</head>
<body>

<div id="menu-section" class="container">
    <h1>Duelos contra a Máquina (Offline)</h1>
    <h2>Escolha o seu Oponente</h2>
    <div id="opponent-list">
        </div>
</div>

<div id="game-section">
    <div id="left-panel">
        <h3>Carta Focada</h3>
        <div id="focused-card-view"><span>Nenhuma carta selecionada</span></div>
    </div>
    <div id="center-panel">
         <div id="board">
            <div id="OpponentHand1" class="card-slot hand"></div><div id="OpponentHand2" class="card-slot hand"></div><div id="OpponentHand3" class="card-slot hand"></div>
            <div id="OpponentAvatar" class="card-slot avatar-slot"></div><div id="OpponentCreature1" class="card-slot battlefield"></div>
            <div id="OpponentCreature2" class="card-slot battlefield"></div><div id="OpponentCreature3" class="card-slot battlefield"></div>
            <div id="OpponentDiscard" class="card-slot discard">Cemitério</div><div id="OpponentDeck" class="card-slot deck">Baralho</div>
            <div id="PlayerAvatar" class="card-slot avatar-slot"></div><div id="PlayerCreature1" class="card-slot battlefield"></div>
            <div id="PlayerCreature2" class="card-slot battlefield"></div><div id="PlayerCreature3" class="card-slot battlefield"></div>
            <div id="PlayerDiscard" class="card-slot discard">Cemitério</div><div id="PlayerDeck" class="card-slot deck">Baralho</div>
            <div id="PlayerHand1" class="card-slot hand"></div><div id="PlayerHand2" class="card-slot hand"></div><div id="PlayerHand3" class="card-slot hand"></div>
       </div>
    </div>
    <div id="right-panel">
        <div id="turn-indicator" class="player-turn"></div>
        <h4>Os Teus Recursos</h4>
        <div class="resource-display">
            <span>Essência: <span id="essenciaMe">25</span></span>
            <span>Prisma: <span id="prismaMe">0</span></span>
        </div>
        <h4>Recursos do Oponente</h4>
        <div class="resource-display">
            <span>Essência: <span id="essenciaOp">25</span></span>
            <span>Prisma: <span id="prismaOp">0</span></span>
        </div>
        <button id="attack-mode-btn" class="main-action-button">Iniciar Ataques</button>
        <button class="main-action-button" style="background-color: #2980b9;" onclick="passTurn()">Passar Turno</button>
        <button onclick="returnToMenu()" class="main-action-button" style="background-color: #c0392b;">Desistir</button>
    </div>
</div>

<script>
    // ===================================================================================
    // REMOVEMOS TODA A LIGAÇÃO À FIREBASE E DEFINIMOS OS DADOS LOCALMENTE
    // ===================================================================================

    // --- DADOS DAS CARTAS (copiado do teu pve_game.html) ---
    const cardData = {
        "WH_01_A_M": { name: "Fenris, the Pack's Fury", type: "Avatar", stats: { Essência: 25 } },
        "WH_02_A_M": { name: "Silas, the Moon Whisperer", type: "Avatar", stats: { Essência: 25 } },
        "WH_03_A_M": { name: "Grandma Willow, Pack Matriarch", type: "Avatar", stats: { Essência: 28 } },
        "WH_04_C_C": { name: "Pack Pup", cost: 1, type: "Creature", stats: { Poder: 1, Vitalidade: 1 } },
        "WH_05_C_C": { name: "Young Pathfinder", cost: 1, type: "Creature", stats: { Poder: 1, Vitalidade: 2 } },
        "WH_06_C_C": { name: "Spirit Wolf", cost: 2, type: "Creature", stats: { Poder: 2, Vitalidade: 1 } },
        "WH_07_C_C": { name: "Howling Berserker", cost: 2, type: "Creature", stats: { Poder: 3, Vitalidade: 1 } },
        "WH_08_C_C": { name: "Pack Ambusher", cost: 2, type: "Creature", stats: { Poder: 2, Vitalidade: 2 } },
        "WH_09_C_I": { name: "Silent Stalker", cost: 2, type: "Creature", stats: { Poder: 2, Vitalidade: 1 } },
        "WH_10_C_R": { name: "Wolf Pack Alpha", cost: 3, type: "Creature", stats: { Poder: 2, Vitalidade: 3 } },
        "WH_11_C_I": { name: "Pack Caller", cost: 3, type: "Creature", stats: { Poder: 2, Vitalidade: 2 } },
        "WH_12_C_C": { name: "Dire Wolf", cost: 3, type: "Creature", stats: { Poder: 4, Vitalidade: 2 } },
        "WH_13_C_I": { name: "Wolf-Kin Guardian", cost: 3, type: "Creature", stats: { Poder: 1, Vitalidade: 5 } },
        "WH_14_C_I": { name: "Lone Wolf", cost: 3, type: "Creature", stats: { Poder: 3, Vitalidade: 3 } },
        "WH_15_C_R": { name: "Shaman of the Full Moon", cost: 4, type: "Creature", stats: { Poder: 3, Vitalidade: 4 } },
        "WH_16_C_I": { name: "Scent Tracker", cost: 4, type: "Creature", stats: { Poder: 3, Vitalidade: 3 } },
        "WH_17_C_C": { name: "Timberline Prowler", cost: 4, type: "Creature", stats: { Poder: 4, Vitalidade: 3 } },
        "WH_18_C_I": { name: "Pack Strategist", cost: 4, type: "Creature", stats: { Poder: 2, Vitalidade: 5 } },
        "WH_19_C_R": { name: "Alpha's Howl", cost: 5, type: "Creature", stats: { Poder: 4, Vitalidade: 4 } },
        "WH_20_C_I": { name: "Moon-Blessed Hunter", cost: 5, type: "Creature", stats: { Poder: 4, Vitalidade: 4 } },
        "WH_21_C_I": { name: "Elder of the Pack", cost: 5, type: "Creature", stats: { Poder: 3, Vitalidade: 3 } },
        "WH_22_C_R": { name: "Greatmaw Wolf", cost: 6, type: "Creature", stats: { Poder: 6, Vitalidade: 5 } },
        "WH_23_C_R": { name: "Spirit-Bound Champion", cost: 6, type: "Creature", stats: { Poder: '*', Vitalidade: '*' } },
        "WH_24_C_M": { name: "World-Wolf Fenrir", cost: 8, type: "Creature", stats: { Poder: 10, Vitalidade: 10 } },
        "WH_60_C_M": { name: "The Great White Wolf", cost: 9, type: "Creature", stats: { Poder: 8, Vitalidade: 8 } }
        // ... (e todas as outras cartas)
    };

    // --- DECK PADRÃO PARA O JOGADOR ---
    const defaultPlayerAvatar = "WH_01_A_M";
    const defaultPlayerDeck = [
        "WH_04_C_C", "WH_04_C_C", "WH_05_C_C", "WH_06_C_C", "WH_07_C_C",
        "WH_08_C_C", "WH_09_C_I", "WH_10_C_R", "WH_12_C_C", "WH_14_C_I"
    ];

    // --- OPONENTES OFFLINE ---
    // Podes adicionar mais oponentes aqui, seguindo o mesmo formato.
    const offlineOpponents = {
        goblin_scout: {
            name: "Batedor Goblin",
            description: "Rápido e irritante, mas frágil. Um bom aquecimento.",
            imageUrl: 'https://i.imgur.com/3Q9fN2c.jpeg', // Imagem de exemplo
            avatarId: "WH_02_A_M",
            deck: ["WH_04_C_C", "WH_04_C_C", "WH_04_C_C", "WH_06_C_C", "WH_06_C_C", "WH_07_C_C", "WH_07_C_C", "WH_05_C_C", "WH_05_C_C", "WH_05_C_C"],
            rewards: {
                dificuldade: "Fácil",
                xp: 10,
                moeda: 5,
                "1ªvitoria": "WH_04_C_C"
            }
        },
        wolf_alpha: {
            name: "Alfa da Matilha",
            description: "Um líder forte que comanda outras feras. Cuidado com os seus aliados.",
            imageUrl: 'https://i.imgur.com/uSti5a7.jpeg', // Imagem de exemplo
            avatarId: "WH_03_A_M",
            deck: ["WH_08_C_C", "WH_10_C_R", "WH_10_C_R", "WH_12_C_C", "WH_14_C_I", "WH_15_C_R", "WH_17_C_C", "WH_19_C_R", "WH_20_C_I", "WH_22_C_R"],
            rewards: {
                dificuldade: "Média",
                xp: 25,
                moeda: 15,
                "1ªvitoria": "WH_10_C_R"
            }
        }
    };


    // --- ESTADO GLOBAL, VARIÁVEIS E CONSTANTES ---
    let gameState = {};
    let cardElementCache = {};
    let activePlayer = 'player';
    let turnCounter = 1;
    let selectedCard = null;
    let currentOpponentId = null; // Para saber as recompensas no final
    const CARD_IMAGE_BASE_URL = "Cartas/";
    let isAttackMode = false;
    let selectedAttacker = null;

    // --- REFERÊNCIAS A ELEMENTOS DA UI ---
    const menuSection = document.getElementById('menu-section');
    const gameSection = document.getElementById('game-section');
    const board = document.getElementById('board');
    const focusedCardView = document.getElementById('focused-card-view');
    const turnIndicator = document.getElementById('turn-indicator');
    const attackModeBtn = document.getElementById('attack-mode-btn');
    const locations = {};
    document.querySelectorAll('.card-slot').forEach(slot => { if (slot.id) locations[slot.id] = slot; });
    
    // --- LÓGICA DE INICIALIZAÇÃO ---

    // Função para mostrar o menu e esconder o jogo
    function showMenu() {
        menuSection.style.display = 'block';
        gameSection.style.display = 'none';
        loadOfflineMenu();
    }

    // Função para carregar os oponentes do objeto local
    function loadOfflineMenu() {
        const opponentListDiv = document.getElementById('opponent-list');
        opponentListDiv.innerHTML = '';
        for (const opponentId in offlineOpponents) {
            const opponent = offlineOpponents[opponentId];
            const rewards = opponent.rewards || {};
            const difficulty = rewards.dificuldade || 'Normal';
            const card = document.createElement('div');
            card.className = 'opponent-card';
            // O onclick agora chama a função para iniciar o jogo localmente
            card.onclick = () => startOfflineGame(opponentId);
            
            card.innerHTML = `
                <img src="${opponent.imageUrl || ''}" alt="${opponent.name}" class="opponent-portrait">
                <div class="opponent-info">
                    <h3>${opponent.name}</h3>
                    <span class="difficulty-tag difficulty-${difficulty.toLowerCase()}">${difficulty}</span>
                    <p class="opponent-description">${opponent.description}</p>
                </div>
                <div class="rewards-preview">
                    <h4>Recompensas</h4>
                    <ul>
                        <li>XP: <strong>${rewards.xp || 0}</strong> | Moedas: <strong>${rewards.moeda || 0}</strong></li>
                        ${rewards['1ªvitoria'] ? `<li>1ª Vitória: <strong>${cardData[rewards['1ªvitoria']]?.name || 'Carta'}</strong></li>` : ''}
                    </ul>
                </div>
            `;
            opponentListDiv.appendChild(card);
        }
    }
    
    // Função para iniciar o jogo com os dados locais
    function startOfflineGame(opponentId) {
        currentOpponentId = opponentId; // Guarda o ID do oponente atual
        const opponentData = offlineOpponents[opponentId];
        if (!opponentData) {
            alert("Oponente não encontrado!");
            return;
        }
        
        // Esconde o menu e mostra o jogo
        menuSection.style.display = 'none';
        gameSection.style.display = 'flex';
        
        setupGameState(defaultPlayerDeck, opponentData);
    }
    
    // O resto do código é o mesmo do teu pve_game.html, com pequenas adaptações
    // para a vitória e derrota.

    function setupGameState(playerDeck, opponentData) {
        // Usa o avatar padrão e o baralho do oponente definido localmente
        gameState = { essenciaMe: 25, essenciaOp: 25, prismaMe: 0, prismaOp: 0, playerDeck: shuffleArray([...playerDeck]), opponentDeck: shuffleArray([...opponentData.deck]), playerAvatarSrc: defaultPlayerAvatar, opponentAvatarSrc: opponentData.avatarId, playerHand: [], };
        turnCounter = 1;
        activePlayer = 'player';
        gameState.prismaMe = 1;
        updateUI();
        for (let i = 0; i < 3; i++) { drawCard('player'); drawCard('opponent'); }
        activePlayer = 'player';
        turnIndicator.textContent = `Turno 1 - Seu Turno`;
        turnIndicator.className = 'player-turn';
        attackModeBtn.disabled = false;
        updateAllStatDisplays();
    }
    
    function checkWinCondition() {
        if (gameState.essenciaOp <= 0) {
            // LÓGICA DE VITÓRIA OFFLINE
            const opponent = offlineOpponents[currentOpponentId];
            const rewards = opponent.rewards || {};
            const rewardMessage = `VITÓRIA!\n\nRecompensas:\n- XP: ${rewards.xp || 0}\n- Moedas: ${rewards.moeda || 0}\n- 1ª Vitória: ${cardData[rewards['1ªvitoria']]?.name || 'Nenhuma'}`;
            alert(rewardMessage);
            returnToMenu(); // Volta para o menu
        } else if (gameState.essenciaMe <= 0) {
            // LÓGICA DE DERROTA OFFLINE
            alert("DERROTA! O seu avatar foi derrotado.");
            returnToMenu(); // Volta para o menu
        }
    }

    function returnToMenu() {
        // Limpa o tabuleiro antes de voltar ao menu para não haver cartas "presas"
        board.innerHTML = `
            <div id="OpponentHand1" class="card-slot hand"></div><div id="OpponentHand2" class="card-slot hand"></div><div id="OpponentHand3" class="card-slot hand"></div>
            <div id="OpponentAvatar" class="card-slot avatar-slot"></div><div id="OpponentCreature1" class="card-slot battlefield"></div>
            <div id="OpponentCreature2" class="card-slot battlefield"></div><div id="OpponentCreature3" class="card-slot battlefield"></div>
            <div id="OpponentDiscard" class="card-slot discard">Cemitério</div><div id="OpponentDeck" class="card-slot deck">Baralho</div>
            <div id="PlayerAvatar" class="card-slot avatar-slot"></div><div id="PlayerCreature1" class="card-slot battlefield"></div>
            <div id="PlayerCreature2" class="card-slot battlefield"></div><div id="PlayerCreature3" class="card-slot battlefield"></div>
            <div id="PlayerDiscard" class="card-slot discard">Cemitério</div><div id="PlayerDeck" class="card-slot deck">Baralho</div>
            <div id="PlayerHand1" class="card-slot hand"></div><div id="PlayerHand2" class="card-slot hand"></div><div id="PlayerHand3" class="card-slot hand"></div>`;
        cardElementCache = {}; // Limpa o cache de elementos de carta
        showMenu();
    }
    
    // Inicia o processo carregando o menu offline quando a página abre
    document.addEventListener('DOMContentLoaded', showMenu);

    // ===================================================================================
    // A PARTIR DAQUI, É O CÓDIGO DE LÓGICA DO JOGO (praticamente inalterado)
    // ===================================================================================
    
    function passTurn() {
        if (activePlayer !== 'player') return;
        if (isAttackMode) toggleAttackMode();
        activePlayer = 'opponent';
        turnIndicator.textContent = `Turno ${turnCounter} - Turno do Oponente`;
        turnIndicator.className = 'opponent-turn';
        attackModeBtn.disabled = true;
        gameState.prismaOp += turnCounter;
        untapAllCards('Opponent');
        drawCard('opponent');
        updateAllStatDisplays();
        setTimeout(startAITurn, 1500);
    }
    function drawCard(player) {
        const deckKey = (player === 'player') ? 'playerDeck' : 'opponentDeck';
        const handPrefix = (player === 'player') ? 'PlayerHand' : 'OpponentHand';
        if (gameState[deckKey].length === 0) { return; }
        const handCards = findCardsInZone(handPrefix);
        if (handCards.length >= 3) {
            if (player === 'player') {
                const newCardSrc = gameState[deckKey][gameState[deckKey].length - 1];
                promptHandChoice(newCardSrc);
            } else {
                gameState[deckKey].pop();
            }
            return;
        }
        const cardSrc = gameState[deckKey].pop();
        const targetSlot = findEmptySlots(handPrefix)[0];
        if (targetSlot) {
            createCard(cardSrc, targetSlot);
            if (player === 'player') gameState.playerHand.push(cardSrc);
            const deckEl = locations[`${player.charAt(0).toUpperCase() + player.slice(1)}Deck`];
            if(deckEl) deckEl.textContent = `Baralho (${gameState[deckKey].length})`;
        }
    }
    function tryPlayCard(cardEl, targetSlot) {
        if (activePlayer !== 'player' || isAttackMode) return;
        const cardInfo = cardData[cardEl.dataset.specificSrc];
        const handSlotId = cardEl.dataset.currentSlot;
        if (!handSlotId.includes('Hand') || !targetSlot.id.includes('Creature')) return;
        if (gameState.prismaMe < cardInfo.cost) { alert("Prisma insuficiente!"); return; }
        gameState.prismaMe -= cardInfo.cost;
        const cardId = cardEl.dataset.specificSrc;
        const handIndex = gameState.playerHand.indexOf(cardId);
        if(handIndex > -1) gameState.playerHand.splice(handIndex, 1);
        moveCard(cardEl, targetSlot);
        selectCard(null);
        updateAllStatDisplays();
    }
    function executeAttack(attacker, target) {
        const attackerPower = parseInt(attacker.dataset.power, 10);
        if (isNaN(attackerPower)) return;
        if (target.dataset.currentSlot.includes('Avatar')) {
            const isPlayerAttacking = attacker.dataset.currentSlot.startsWith('Player');
            const targetEssenceKey = isPlayerAttacking ? 'essenciaOp' : 'essenciaMe';
            gameState[targetEssenceKey] -= attackerPower;
        } else {
            const targetPower = parseInt(target.dataset.power, 10);
            target.dataset.vitality -= attackerPower;
            attacker.dataset.vitality -= targetPower;
            updateCardStatsDisplay(target);
            updateCardStatsDisplay(attacker);
            if (target.dataset.vitality <= 0) moveCardToDiscard(target);
            if (attacker.dataset.vitality <= 0) moveCardToDiscard(attacker);
        }
        attacker.classList.add('tapped');
        updateAllStatDisplays();
        checkWinCondition();
    }
    function toggleAttackMode() {
        isAttackMode = !isAttackMode;
        if (isAttackMode) {
            attackModeBtn.textContent = 'Terminar Ataques';
            attackModeBtn.classList.add('attack-mode-active');
            board.classList.add('attack-mode-active');
            selectCard(null);
        } else {
            attackModeBtn.textContent = 'Iniciar Ataques';
            attackModeBtn.classList.remove('attack-mode-active');
            board.classList.remove('attack-mode-active');
            cancelAttackSelection();
        }
    }
    function cancelAttackSelection() {
        if (selectedAttacker) {
            selectedAttacker.classList.remove('attacker-selected');
            selectedAttacker = null;
        }
        document.querySelectorAll('.valid-target').forEach(el => el.classList.remove('valid-target'));
    }
    function handleCardClick(cardEl) {
        if (activePlayer !== 'player') return;
        if (isAttackMode) {
            const isPlayerCreature = cardEl.dataset.currentSlot.startsWith('PlayerCreature');
            if (selectedAttacker) {
                if (findCardInSlot(cardEl.dataset.currentSlot).parentElement.classList.contains('valid-target')) {
                    executeAttack(selectedAttacker, cardEl);
                    cancelAttackSelection();
                } else {
                    cancelAttackSelection();
                }
            } else {
                if (isPlayerCreature && !cardEl.classList.contains('tapped')) {
                    selectedAttacker = cardEl;
                    cardEl.classList.add('attacker-selected');
                    findCardsInZone('OpponentCreature').forEach(target => target.parentElement.classList.add('valid-target'));
                    const opponentAvatarSlot = findCardInSlot('OpponentAvatar')?.parentElement;
                    if (opponentAvatarSlot) opponentAvatarSlot.classList.add('valid-target');
                }
            }
        } else {
            if (cardEl.dataset.currentSlot.startsWith('Player')) {
                selectCard(cardEl);
            }
        }
    }
    async function startAITurn() {
        await aiPlayCards();
        await new Promise(r => setTimeout(r, 800));
        await aiAttackPhase();
        await new Promise(r => setTimeout(r, 800));
        activePlayer = 'player';
        turnCounter++;
        gameState.prismaMe += turnCounter;
        turnIndicator.textContent = `Turno ${turnCounter} - Seu Turno`;
        turnIndicator.className = 'player-turn';
        attackModeBtn.disabled = false;
        untapAllCards('Player');
        drawCard('player');
        updateAllStatDisplays();
    }
    async function aiPlayCards() {
        const aiHandCards = findCardsInZone('OpponentHand');
        const emptySlots = findEmptySlots('OpponentCreature');
        if (aiHandCards.length === 0 || emptySlots.length === 0) return;
        const playableCards = aiHandCards.filter(cardEl => cardData[cardEl.dataset.specificSrc].cost <= gameState.prismaOp).sort((a, b) => cardData[b.dataset.specificSrc].cost - cardData[a.dataset.specificSrc].cost);
        if (playableCards.length > 0) {
            const cardToPlay = playableCards[0];
            const cardInfo = cardData[cardToPlay.dataset.specificSrc];
            const targetSlot = emptySlots[0];
            gameState.prismaOp -= cardInfo.cost;
            moveCard(cardToPlay, targetSlot);
            updateAllStatDisplays();
        }
    }
    async function aiAttackPhase() {
        const aiAttackers = findCardsInZone('OpponentCreature').filter(c => !c.classList.contains('tapped'));
        if (aiAttackers.length === 0) return;
        for (const attacker of aiAttackers) {
            const playerCreatures = findCardsInZone('PlayerCreature');
            let target = null;
            if (playerCreatures.length > 0) {
                target = playerCreatures[Math.floor(Math.random() * playerCreatures.length)];
            } else {
                target = findCardInSlot('PlayerAvatar');
            }
            if (target) {
                executeAttack(attacker, target);
                await new Promise(r => setTimeout(r, 1200));
            }
        }
    }
    function shuffleArray(array) {
        let currentIndex = array.length, randomIndex;
        while (currentIndex != 0) {
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex--;
            [array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]];
        }
        return array;
    }
    function updateUI() {
        if(board) board.querySelectorAll('.card').forEach(cardEl => cardEl.remove());
        cardElementCache = {};
        if (gameState.playerAvatarSrc) createCard(gameState.playerAvatarSrc, locations.PlayerAvatar);
        if (gameState.opponentAvatarSrc) createCard(gameState.opponentAvatarSrc, locations.OpponentAvatar);
        if(locations.PlayerDeck) locations.PlayerDeck.textContent = `Baralho (${gameState.playerDeck.length})`;
        if(locations.OpponentDeck) locations.OpponentDeck.textContent = `Baralho (${gameState.opponentDeck.length})`;
    }
    function createCard(specificSrc, targetSlot) {
        if (!targetSlot || !cardData[specificSrc]) { return null; }
        const cardEl = document.createElement('div');
        cardEl.className = 'card';
        cardEl.innerHTML = `<img src="${CARD_IMAGE_BASE_URL}${specificSrc}.png" alt="${cardData[specificSrc].name}" onerror="this.src='https://placehold.co/100x140?text=${specificSrc}';">`;
        cardEl.dataset.specificSrc = specificSrc;
        cardEl.dataset.currentSlot = targetSlot.id;
        const cardInfo = cardData[specificSrc];
        if (cardInfo?.stats?.Poder) {
            cardEl.dataset.power = cardInfo.stats.Poder;
            cardEl.dataset.vitality = cardInfo.stats.Vitalidade;
            updateCardStatsDisplay(cardEl);
        }
        const uniqueId = `${specificSrc}-${Date.now()}-${Math.random()}`;
        cardElementCache[uniqueId] = cardEl;
        board.appendChild(cardEl);
        alignCardToSlot(cardEl, targetSlot);
        cardEl.addEventListener('click', (e) => {
            e.stopPropagation();
            handleCardClick(e.currentTarget);
        });
        return cardEl;
    }
    function promptHandChoice(newCardId) {
        alert(`Mão cheia! A carta comprada é "${cardData[newCardId].name}". Clique numa carta na sua mão para a devolver ao fundo do baralho.`);
        const handCards = findCardsInZone('PlayerHand');
        const clickHandler = (event) => {
            const clickedCard = event.currentTarget;
            const clickedCardId = clickedCard.dataset.specificSrc;
            const indexToRemove = gameState.playerHand.indexOf(clickedCardId);
            if(indexToRemove > -1) {
                const [removedCard] = gameState.playerHand.splice(indexToRemove, 1);
                gameState.playerDeck.unshift(removedCard);
            }
            const cardCacheId = Object.keys(cardElementCache).find(key => cardElementCache[key] === clickedCard);
            if(cardCacheId) delete cardElementCache[cardCacheId];
            clickedCard.remove();
            const drawnCard = gameState.playerDeck.pop();
            const emptySlot = findEmptySlots('PlayerHand')[0];
            createCard(drawnCard, emptySlot);
            gameState.playerHand.push(drawnCard);
            handCards.forEach(card => {
                card.parentElement.classList.remove('valid-target');
                card.removeEventListener('click', clickHandler);
            });
            const deckEl = locations.PlayerDeck;
            if(deckEl) deckEl.textContent = `Baralho (${gameState.playerDeck.length})`;
        };
        handCards.forEach(card => {
            card.parentElement.classList.add('valid-target');
            card.addEventListener('click', clickHandler, { once: true });
        });
    }
    attackModeBtn.addEventListener('click', toggleAttackMode);
    for (let i = 1; i <= 3; i++) {
        const slotId = `PlayerCreature${i}`;
        if(locations[slotId]) {
            locations[slotId].addEventListener('click', () => {
                if(!isAttackMode && selectedCard && selectedCard.dataset.currentSlot.startsWith('PlayerHand')) {
                    tryPlayCard(selectedCard, locations[slotId]);
                }
            });
        }
    }
    function alignCardToSlot(cardEl, targetSlot) {
        const targetRect = targetSlot.getBoundingClientRect();
        const boardRect = board.getBoundingClientRect();
        cardEl.style.left = `${targetRect.left - boardRect.left}px`;
        cardEl.style.top = `${targetRect.top - boardRect.top}px`;
        cardEl.style.width = `${targetRect.width}px`;
        cardEl.style.height = `${targetRect.height}px`;
    }
    function selectCard(cardEl) {
        if (isAttackMode) return;
        if (selectedCard) selectedCard.classList.remove('selected');
        if (selectedCard === cardEl || !cardEl) {
            selectedCard = null;
            focusedCardView.innerHTML = '<span>Nenhuma carta selecionada</span>';
        } else {
            selectedCard = cardEl;
            selectedCard.classList.add('selected');
            const cardSrc = cardEl.dataset.specificSrc;
            focusedCardView.innerHTML = `<img src="${CARD_IMAGE_BASE_URL}${cardSrc}.png" alt="${cardData[cardSrc].name}">`; 
        }
    }
    function moveCard(cardEl, targetSlot) {
        alignCardToSlot(cardEl, targetSlot);
        cardEl.dataset.currentSlot = targetSlot.id;
    }
    function moveCardToDiscard(cardEl) {
        const ownerPrefix = cardEl.dataset.currentSlot.startsWith('Player') ? 'Player' : 'Opponent';
        const discardSlot = locations[`${ownerPrefix}Discard`];
        const uniqueId = Object.keys(cardElementCache).find(key => cardElementCache[key] === cardEl);
        if(uniqueId) delete cardElementCache[uniqueId];
        if(discardSlot) {
             alignCardToSlot(cardEl, discardSlot);
               setTimeout(() => cardEl.remove(), 500);
        } else {
             cardEl.remove();
        }
    }
    function untapAllCards(ownerPrefix) {
        findCardsInZone(ownerPrefix + 'Creature').forEach(card => card.classList.remove('tapped'));
    }
    function updateAllStatDisplays() {
        if(document.getElementById('essenciaMe')) document.getElementById('essenciaMe').textContent = gameState.essenciaMe;
        if(document.getElementById('essenciaOp')) document.getElementById('essenciaOp').textContent = gameState.essenciaOp;
        if(document.getElementById('prismaMe')) document.getElementById('prismaMe').textContent = gameState.prismaMe;
        if(document.getElementById('prismaOp')) document.getElementById('prismaOp').textContent = gameState.prismaOp;
    }
    function updateCardStatsDisplay(cardEl) {
        let statsDisplay = cardEl.querySelector('.card-stats-display');
        if (!statsDisplay) {
            statsDisplay = document.createElement('div');
            statsDisplay.className = 'card-stats-display';
            cardEl.appendChild(statsDisplay);
        }
        statsDisplay.textContent = `${cardEl.dataset.power} / ${cardEl.dataset.vitality}`;
    }
    function findEmptySlots(prefix) {
        const slots = [];
        for (let i = 1; i <= 3; i++) {
            const slotId = `${prefix}${i}`;
            if (!findCardInSlot(slotId)) slots.push(locations[slotId]);
        }
        return slots;
    }
    function findCardsInZone(prefix) {
        return Object.values(cardElementCache).filter(c => c.dataset.currentSlot?.startsWith(prefix));
    }
    function findCardInSlot(slotId) {
        return Object.values(cardElementCache).find(c => c.dataset.currentSlot === slotId);
    }
    Object.assign(window, { passTurn, returnToMenu });

</script>
</body>
</html>